<template>
	<view>
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">个人设置</block>
		</cu-custom>
		<form v-if="userInfo">
			<view class="cu-form-group margin-top">
				<view class="title">头像</view>
				<u-avatar :src="userInfo.avatar" :show-sex='true' :sex-icon='userInfo.sex' @click="chooseAvatar"></u-avatar>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title">昵称</view>
				<input placeholder="请输入昵称" name="input" v-model="userInfo.nickName" style="text-align: right;"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">性别</view>
				<picker @change="PickerChange" :value="index" :range="picker">
					<view class="picker">
						{{index>-1?picker[index]:'选择性别'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">生日</view>
				<picker mode="date" :value="userInfo.birthday" start="1900-09-01" end="2050-09-01" @change="DateChange">
					<view class="picker">
						{{userInfo.birthday}}
					</view>
				</picker>
			</view>
			<!-- <view class="cu-form-group margin-top">
				<view class="title">开关选择</view>
				<switch @change="SwitchA" :class="switchA?'checked':''" :checked="switchA?true:false"></switch>
			</view> -->
			<!-- !!!!! placeholder 在ios表现有偏移 建议使用 第一种样式 -->
			<view class="cu-form-group margin-top">
				<textarea maxlength="-1" :disabled="modalName!=null" @input="textareaAInput" placeholder="个人简介" v-model="userInfo.brief"></textarea>
			</view>
			
			<u-button type="primary" shape="square" @click="baocun">保存</u-button>
		</form>
	</view>
</template>

<script>
	import {
		univerifyLogin
	} from '@/common/univerify.js'
	export default {
		data() {
			return {
				index: 0,
				picker: ['男', '女', '保密'],		
				modalName: null,
				userInfo:{
					nickName:'',
					sex:'man',
					birthday: '请选择',
					brief: '',	
				}
			};
		},
		onLoad() {
		
			let uniIdToken = uni.getStorageSync('uni_id_token')
			if (uniIdToken) {
				uniCloud.callFunction({
					name: 'user-center',
					data: {
						action: 'checkToken',
					},
					success: (e) => {
						console.log('checkToken success个人设置', e);
						this.userInfo=e.result.userInfo
						if(this.userInfo.sex=='man'){
							this.index=0
						}else if(this.userInfo.sex=='woman'){
							this.index=1
						}else{
							this.index=2
						}
						if (e.result.code > 0) {
							//token过期或token不合法，重新登录
							if (this.forcedLogin) {
								uni.reLaunch({
									url: '../login/login'
								});
							} else {
								uni.navigateTo({
									url: '../login/login'
								});
							}
						}
					},
					fail(e) {
						uni.showModal({
							content: JSON.stringify(e),
							showCancel: false
						})
					}
				})
			} else {
				this.guideToLogin()
			}
		},
		created() {
					// 监听从裁剪页发布的事件，获得裁剪结果
					uni.$on('uAvatarCropper', path => {
						
						let ext = path.split('.').pop()
						const options = {
							filePath: path,
							cloudPath: 'avatar'+Date.now() + '.' + ext
						}
						uniCloud.uploadFile({
							...options,
							onUploadProgress(e) {
								// console.log(e)
							}
						}).then(res => {
							
							// console.log(res);
							// uni.showModal({
							// 	content: '图片上传成功，fileId为：' + res.fileID,
							// 	showCancel: false
							// })
							
							uniCloud.callFunction({
								name: 'user-center',
								data: {
									action:'setAvatar',
									params:{
										avatar:res.fileID
									}
								},
								success:(e)=> {
									 console.log(e,'eeeee')
									this.userInfo.avatar = res.fileID;
								},
								fail(e) {
									uni.showModal({
										content: JSON.stringify(e),
										showCancel: false
									})
								}
							})
							
						}).catch((err) => {
							
							console.log(err);
							if (err.message !== 'Fail_Cancel') {
								uni.showModal({
									content: `图片上传失败，错误信息为：${err.message}`,
									showCancel: false
								})
							}
						})

					})
		},
		methods: {
			PickerChange(e) {
				this.index = e.detail.value
				if(this.picker[this.index]=='男'){
					this.userInfo.sex='man'
				}
				else if(this.picker[this.index]=='女'){
					this.userInfo.sex='woman'
				}else{
					this.userInfo.sex='保密'
				}
			},
			DateChange(e) {
				this.userInfo.birthday = e.detail.value
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			textareaAInput(e) {
				this.userInfo.brief = e.detail.value
			},
			guideToLogin() {
				let that =this;
				uni.showModal({
					title: '未登录',
					content: '您未登录，需要登录后才能继续',
					/**
					 * 如果需要强制登录，不显示取消按钮
					 */
					showCancel: !this.forcedLogin,
					success: (res) => {
						if (res.confirm) {
							that.goToLogin()
						}
					}
				});
			},
			goToLogin(){
				univerifyLogin().catch((err) => {
					// console.log(err,'???')
					if (err === false) return;
					/**
					 * 如果需要强制登录，使用reLaunch方式
					 */
					if (this.forcedLogin) {
						uni.reLaunch({
							url: '../login/login'
						});
					} else {
						uni.navigateTo({
							url: '../login/login'
						});
					}
				})
			},
			chooseAvatar() {
				console.log(this.$u.route)
				// 此为uView的跳转方法，详见"文档-JS"部分，也可以用uni的uni.navigateTo
				this.$u.route({
					// 关于此路径，请见下方"注意事项"
					url: '/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
					// 内部已设置以下默认参数值，可不传这些参数
					params: {
						// 输出图片宽度，高等于宽，单位px
						destWidth: 300,
						// 裁剪框宽度，高等于宽，单位px
						rectWidth: 200,
						// 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
						fileType: 'jpg',
					}
				})				
			},
			baocun(){
				let options={
					nickName:this.userInfo.nickName,
					sex:this.userInfo.sex,
					birthday:this.userInfo.birthday=='请选择'?'':this.userInfo.birthday,
					brief:this.userInfo.brief
					
				}
				// console.log(options)
				
				uniCloud.callFunction({
					name:'user-center',
					data:{
						action:'updateUser',
						params:options
					},
					success: (e) => {
						console.log(e)
						uni.showToast({
							title:'更新成功~'
						})
						uni.$emit('checkUserIngo',true)
						setTimeout(()=>{
							uni.switchTab({
								url:'./index'
							})
						},1000)
					},
					fail: (e) => {
						console.log(e,'更新个人信息失败')
					}
				})
			},
			
			
		}
	}
</script>

<style>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
</style>
